﻿using CSharpTest;
using MQTTnet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MQTTServerTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            InitMQTT();
        }

        public async void InitMQTT()
        {
            var mqttServer = new MQTTServerHelper();
            // 定义消息接收事件处理
            mqttServer.OnMessageReceived += (sender, e) =>
            {
                var message = e.ApplicationMessage;
                ShowLog($"服务器转发消息到主题: {message.Topic}, 内容: {message.ConvertPayloadToString()}");
            };
            // 启动服务器（本地 IP，端口 1883）
            string ip = "127.0.0.1";
            int port = 8080;

            ShowLog($"启动 MQTT 服务器 {ip}:{port}...");
            await mqttServer.StartMqtServer(ip, port);
        }

        public void ShowLog(string msg)
        {
            string date = DateTime.Now.ToString();

            string text = $"[{date}]{msg}\n";

            if (richTextBox_log.InvokeRequired)
            {
                // 跨线程时通过委托调用自身
                richTextBox_log.Invoke(new Action(() =>
                {
                    richTextBox_log.AppendText(text);
                }));
            }
            else
            {
                // 当前已是 UI 线程，直接操作
                richTextBox_log.AppendText(text);
            }

        }
    }
}
